package org.dtrd.config.pay;

import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.cert.CertificatesManager;
import com.wechat.pay.contrib.apache.httpclient.exception.HttpCodeException;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import lombok.Data;
import org.dtrd.config.wechat.config.WechatUtil;
import org.dtrd.config.wechat.entity.bean.pay.WechatPayConfig;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;

/**
 * @author xiao
 * @date 2022/6/6 11:16 AM
 */
@Data
public final class PayConfig {

    private static Integer validTime;

    private static WechatPayConfig wechatPay;

    public static void setValidTime(Integer validTime) {
        PayConfig.validTime = validTime;
    }

    public static Integer getValidTime() {
        return validTime;
    }

    public static void setWechatPay(String wechatPayMchId, String wechatPayNotifyUrl, String serialNo, String privateKeyV2, String privateKeyV3) {
        PayConfig.wechatPay = new WechatPayConfig(wechatPayMchId, wechatPayNotifyUrl, serialNo, privateKeyV2, privateKeyV3);
        try {
            CertificatesManager.getInstance().putMerchant(wechatPayMchId, new WechatPay2Credentials(wechatPayMchId, new PrivateKeySigner(serialNo, getMerchantPrivateKey())),
                    privateKeyV3.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        } catch (HttpCodeException e) {
            e.printStackTrace();
        }
        System.out.println("WechatUtil.setWechatPay " + wechatPayNotifyUrl);
    }


    public static PrivateKey getMerchantPrivateKey() throws IOException {
        InputStream inputStream2 = readFile("pay/apiclient_key.pem");
        return PemUtil.loadPrivateKey(inputStream2);
    }

    private static InputStream readFile(String path) throws IOException {
        ClassPathResource resource = new ClassPathResource(path);
        return resource.getInputStream();
    }

    public static WechatPayConfig getWechatPayConfig() {
        return wechatPay;
    }
}
